/*
 * Copyright (c) 2012 Johan Fylling
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy 
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights 
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 * copies of the Software, and to permit persons to whom the Software is 
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in 
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 * THE SOFTWARE.
 */

part of engine;


/**
 * Clipping Contact Detector as described by Code Zealot [http://www.codezealot.org/archives/394 (2012-09-06)].
 */
class ClippingContactDetector implements ContactDetector {
  
  /** See [ContactDetector.detectContact]. */
  ContactManifold detectContact(DynamicBody body1, 
                                DynamicBody body2, 
                                Vector2 penetration) {
    Collidable c1 = body1.collidable;
    Collidable c2 = body2.collidable;
    
    ContactManifold manifold;
    Vector2 normal = penetration.normalized();
    
    ContactFeature cf1 = c1.getFarthestFeature(body1, normal);
    if (cf1 is ContactVertex) {
      manifold = new ContactManifold(-normal);
      manifold.points.add(new ContactPoint(new Vector2.copy((cf1 as ContactVertex).vertex), penetration.length));
      return manifold;
    }
    
    ContactFeature cf2 = c2.getFarthestFeature(body2, -normal);
    if (cf2 is ContactVertex) {
      manifold = new ContactManifold(normal);
      manifold.points.add(new ContactPoint(new Vector2.copy((cf2 as ContactVertex).vertex), penetration.length));
      return manifold;
    }
    
    // Identify reference- and incident edges.
    
    ContactEdge reference = (cf1 as ContactEdge);
    ContactEdge incident = (cf2 as ContactEdge);
    
    bool flip = false;
    if (reference.dot(normal).abs() > incident.dot(normal).abs()) {
      flip = true;
      reference = (cf2 as ContactEdge);
      incident = (cf1 as ContactEdge);
    }
    manifold = new ContactManifold(flip ? -normal : normal);
    
    // Clip.
    
    reference.normalize();
    
    num o1 = reference.dot(reference.vertex1);
    List<Vector2> clippedPoints = _clip(incident.vertex1, incident.vertex2, reference, o1);
    if (clippedPoints.length < 2) {
      return manifold;
    }
    
    num o2 = reference.dot(reference.vertex2);
    clippedPoints = _clip(clippedPoints[0], clippedPoints[1], -reference, -o2);
    if (clippedPoints.length < 2) {
      return manifold;
    }
    
    Vector2 referenceNormal = reference.cross2(-1.0).normalized();
    num max = referenceNormal.dot(reference.max);
    for (Vector2 point in clippedPoints) {
      num depth = referenceNormal.dot(point) - max;
      if (depth >= 0.0) {
        manifold.points.add(new ContactPoint(point, depth));
      }
    }
    
    DebugPainter debugPainter = (ServiceManager.getService("DebugPainter") as DebugPainter);
    if (debugPainter != null) {
      debugPainter.debugDrawLine(reference.vertex1, 
                                 reference.vertex2,
                                 style:"green");
      debugPainter.debugDrawLine(incident.vertex1, 
                                 incident.vertex2,
                                 style:"red");
    }
    
    return manifold;
  }
  
  /** Clipp points [v1] [v2] to fall within [o] in the direction of [n]. */
  List<Vector2> _clip (Vector2 v1, Vector2 v2, Vector2 n, num o) {
    List<Vector2> clippedPoints = new List<Vector2>();
    num d1 = n.dot(v1) - o;
    num d2 = n.dot(v2) - o;
    
    if (d1 >= 0.0) {
      clippedPoints.add(v1);
    }
    if (d2 >= 0.0) {
      clippedPoints.add(v2);
    }
    
    if (d1 * d2 < 0.0) {
      Vector2 e = v2 - v1;
      num u = d1 / (d1 - d2);
      e.mul(u);
      e.add(v1);
      clippedPoints.add(e);
    }
    
    return clippedPoints;
  }
}
